const root = document.getElementById('codeRoot');

/**
 * 启动服务
 */
(function runSocket() {

  var logList = [];

  this.ws = (function () {
    var defaultPort = 11996;
    if (window.wsPort) {
      defaultPort = window.wsPort;
    }

    var ws = new WebSocket('ws://localhost:' + defaultPort);
    ws.onopen = () => {
      console.log('[PageLog]:已建立数据pageLog打印服务');
      ws.send('SIGN_PAGE_LOG');
    }

    ws.onclose = (event) => {
      console.log('[PageLog]:已关闭服务');
    }
    ws.onerror = (event) => {
      console.log('[PageLog]:无法连接');
    }

    ws.onmessage = (message) => {
      if (message.data === 'PAGE_LOG_CLEAR') {
        root.innerHTML = '';
        console.clear();
        logList = [];
      } else {
        this.writeLog(message.data)
      }
    }
    return ws;
  })();

  /**
   * 书写日志
   * @param code
   */
  this.writeLog = function (code) {
    var parseCode = JSON.parse(code);

    if (Array.isArray(parseCode)) {
      // parseCode = ["{"msg":111,"opt":{}}","{"msg":111,"opt":{}}",...]
      parseCode.forEach(itemJson => {
        // itemJson {"msg":[111,"sss",{"name":"ss","age":1},[1,"212",{"s":1}]],"opt":{}}
        try {
          var codeItem = JSON.parse(itemJson);
          let data = codeItem.msg || '';
          var logTitle = 'Log Info';
          if (Array.isArray(data)) {
            if(typeof data[0] === 'string' && data[0].includes('http')){
              // 提取打印位置信息
              logTitle = data.shift();
            }
            console.log('[PageLog]: ', ...data);
            data.length > 1 ? this.appendEditor(data, logTitle) : this.appendEditor(data[0], logTitle);
          } else {
            this.appendEditor(data, logTitle);
          }
        } catch (e) {
          this.appendEditor(JSON.stringify({
            ERROR: '无法解析！'
          }));
        }
      })
      return false;
    }

    if (typeof parseCode === 'object') {
      const data = parseCode.msg || '';
      let logTitle = 'Log Info';

      if (Array.isArray(data)) {
        if(typeof data[0] === 'string' && data[0].includes('http')){
          // 提取打印位置信息
          logTitle = data.shift();
        }
        console.log('[PageLog]: ', ...data);
        data.length > 1 ? this.appendEditor(data, logTitle) : this.appendEditor(data[0], logTitle);

      } else {
        this.appendEditor(data, logTitle);
      }
      // root.innerHTML = parseCode.msg;
      return false;
    }
  }

  /**
   *
   * @param data
   * @param logTitle
   */
  this.appendEditor = function (data, logTitle = 'Log Info') {
    if (logList.length < 1) {
      root.innerHTML = '';
    }
    try {
      if(JSON.stringify(data).length < 20){
        this.appendLine(data, logTitle);
        return;
      }
    }catch (e) {

    }
    // <div class="itemBox">
    //     <dl>
    //       <dt>2</dt>
    //       <dd>
    //       </dd>
    //     </dl>
    //     <iframe src="/LogIframe.html" frameborder="0" class="logIframe"></iframe>
    //   </div>
    var $itemBox = document.createElement('div');
    $itemBox.classList.add('itemBox');

    var $dl = document.createElement('dl');
    $dl.innerHTML = '<dt>' + (logList.length + 1) + '</dt><dd>' + logTitle + '</dd>';

    var $iframe = document.createElement('iframe');
    $iframe.src = '/LogIframe.html';
    $iframe.frameborder = '0';
    $iframe.classList.add('logIframe');
    /**
     *通过postMessage发送数据
     */
    $iframe.addEventListener('load', function () {
      // 获取iframe窗口对象       
      var iframeWin = this.contentWindow;

      // 向该窗口发送消息      
      iframeWin.postMessage(JSON.stringify(data), window.location.origin);
    })

    $itemBox.appendChild($dl);
    $itemBox.appendChild($iframe);
    root.appendChild($itemBox);
    // 追加
    logList.push(data);
  }

  /**
   * 单行输入到页面
   */
  this.appendLine = function (data, logTitle = 'Log Info') {
    // <dl class="lineInfo">
    //     <dt>
    //       <span class="orderNum">1</span>
    //       <span class="lineLog">1dfadf</span>
    //     </dt>
    //     <dd>Log At: http://</dd>
    //   </dl>
    var $dlLog = document.createElement('dl');
    $dlLog.classList.add('lineInfo');
    $dlLog.innerHTML = '<dt>' +
      '<span class="orderNum">' + (logList.length + 1) + '</span>' +
      '<span class="lineLog">' + data + '</span>' +
      '</dt>' +
      '<dd>' + logTitle + '</dd>';
    root.appendChild($dlLog);
    // 追加
    logList.push(data);

  }



})();


